import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Demo3 {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("要扫描的路径：");
        String root = scanner.next();
        File file = new File(root);
        if(!file.isDirectory()){
            System.out.println("不是目录");
            return;
        }
        System.out.println("输入查找的字符：");
        String word = scanner.next();
        List<File> ans = new ArrayList<>();
        find(file,word,ans);
        System.out.println("=====");
        for (File f: ans) {
            System.out.println(f.getCanonicalFile());
        }
        System.out.println("=====");
    }
    private static void find(File root, String word, List<File> ans){
        File[] f = root.listFiles();
        if(f == null || f.length == 0)
            return;
        for (File file: f) {
            if(file.isDirectory()){
                find(file,word,ans);
            }else {
                if(isValid(file,word))
                    ans.add(file);
            }
        }
    }

    static boolean isValid(File f, String word){
        StringBuilder s = new StringBuilder();
        try(InputStream inputStream = new FileInputStream(f);
        Scanner scanner = new Scanner(inputStream, "UTF-8")) {
            while(scanner.hasNextLine()){
                s.append(scanner.nextLine());
                s.append("\r\t");
            }
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
        return s.indexOf(word) != -1;
    }
}
